package com.urchin.avatarhero.questview;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.urchin.avatarhero.R;
import com.urchin.avatarhero.util.SQLiteHandler;
import com.urchin.avatarhero.util.Utilities;
import com.urchin.avatarhero.util.cal.CalBlob;
import com.urchin.avatarhero.util.cal.CalendarHandler;

/**********************************************************************
AvatarHero - A task management RPG Android Application
Copyright (C) 2013  Peter Clay

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/

public class CurQuestDialog extends DialogFragment {
	ArrayAdapter<String> qadapter;
	Activity act;

	public CurQuestDialog() {

	}
	
	// Returns a new instance of this class
	static CurQuestDialog newInstance(int num, int c, int e, int i, ArrayAdapter<String> qa, Activity a, int diff) {
		CurQuestDialog f = new CurQuestDialog();

		// Supply num input as an argument.
	    Bundle args = new Bundle();
	    args.putInt("num", num);
	    args.putInt("calid", c);
	    args.putInt("eventid", e);
	    args.putInt("instanceid", i);
	    args.putString("curdiff", String.valueOf(diff));
	    f.setArguments(args);
	    
	    f.qadapter = qa;
	    f.act = a;
	        
	    return f;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		LayoutInflater i = act.getLayoutInflater();
		View testView = (View)i.inflate(R.layout.dialog_qcur, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		
		EditText editTextDiff = (EditText) testView.findViewById(R.id.curq_diff);
		editTextDiff.setHint(this.getArguments().getString("curdiff"));
		// Use the inflater to set the dialog view
		builder
			.setTitle(R.string.quest_dialog_cur)
			.setView(testView)
			.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					moveQuest();
				}
			})
			.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					CurQuestDialog.this.getDialog().cancel();					
				}
			});	
		
		return builder.create();
	}
	
	public void moveQuest() {
		int cid = this.getArguments().getInt("calid");
		int eid = this.getArguments().getInt("eventid");
		int iid = this.getArguments().getInt("instanceid");
		
		// Get the diff level and set it
		EditText editText = (EditText) (this.getDialog().findViewById(R.id.curq_diff));
		int level = 0;
		RadioGroup rg = (RadioGroup) this.getDialog().findViewById(R.id.quest_ack);
		RadioButton rb = null;
		
		// Get the selected radio button
		int selid = rg.getCheckedRadioButtonId();
		if(selid != -1) {
			rb = (RadioButton) this.getDialog().findViewById(selid);
		} else {
			rb = null;
		}

		// If the user didn't change the difficulty, grab what's in the hint
		if(editText.getText().length() == 0) {
			try {
				level = Integer.parseInt((String) editText.getHint());
			} catch(NumberFormatException e) {
				level = 0;			// Set to 0
			}
		} else {
			// Try to parse the string. If not an Integer, just set to zero
			try {
				level = Integer.parseInt(editText.getText().toString().trim());
			} catch(NumberFormatException e) {
				level = 0;			// Set to 0
			}
		}
		
		if(rb != null) {	// If either complete or fail was selected
			if((level <= 10) && (level > 0)) { 	// If the difficulty level is between 1 and 10
				
				// Now we have to update the GUI list in place
				// Get the Calendar data
			     CalendarHandler calhandle = new CalendarHandler(CurQuestDialog.this.act);
			     // Get the Event and Instance data
			     ArrayList<CalBlob> cdata = calhandle.buildCalData(calhandle.getEvents(), calhandle.getInstances());
			     Utilities util = new Utilities(act);
									
				// Remove it before we add it (Yeah, it's a bit weird, but we need to remove it while the database still says it's a difficult 0)
				for(CalBlob caldata : cdata) {
					if( (caldata.getCalid() == cid) && (caldata.getInstanceid() == iid) && (caldata.getEventid() == eid)) {		// Event and Instance match
						qadapter.remove(util.convertToStrPattern(caldata, "caldisp"));		// Clear the adapter
						qadapter.notifyDataSetChanged();
						break;
					}
				}
						
				// Now update in the database
				// Get the Quest Id
				SQLiteHandler dbHandler = new SQLiteHandler(this.getDialog().getContext());
				dbHandler.opendb();
								
				if(rb.getText().equals(getResources().getString(R.string.quest_dialog_cur_compq))) {		// Complete
					int exp = util.genExp(level);
					dbHandler.updateQuest(cid, eid, iid, level, exp, -1, 1);		// Mark as complete with relevant exp and items
					Toast.makeText(act.getApplicationContext(),"Complete: " + String.valueOf(exp),Toast.LENGTH_SHORT).show();
					
					util.increaseExp(act.getApplicationContext(), exp);			// Add the experience to the total
					 					 
				} else if(rb.getText().equals(getResources().getString(R.string.quest_dialog_cur_failq))) {	// Fail
					Toast.makeText(act.getApplicationContext(),"Fail",Toast.LENGTH_SHORT).show();
					dbHandler.updateQuest(cid, eid, iid, level, 0, -1, -1);		// Mark as failure no exp and no items
				
				} else {
					Toast.makeText(act.getApplicationContext(),"Unknown",Toast.LENGTH_SHORT).show();
				}
				dbHandler.closedb();
			} else {
				Toast.makeText(act.getApplicationContext(),"Diff. must be 1-10",Toast.LENGTH_SHORT).show();
			}
		}
	}
}
